package com.gofaraway.service.juc;

import java.util.concurrent.*;

/**
 * @author ChenPeng
 * @Date 2024/3/26 19:53
 */
public class CompletableFutureUseDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "---come in");
            int result = ThreadLocalRandom.current().nextInt(10);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (result > 5) { //模拟产生异常情况
                throw new RuntimeException();
            }
            System.out.println("----------1秒钟后出结果：" + result);
            return result;
        }, executorService).whenComplete((v, e) -> {//执行完成后回调
            if (e == null) {
                System.out.println("计算完成 更新系统" + v);
            }
        }).exceptionally(e -> {
            System.out.println("异常情况：" + e.getCause() + " " + e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "先去完成其他任务");

        //用完线程池 记得关闭
        executorService.shutdown();
    }
}
